package com.syyo.admin.config.security.config;

import com.syyo.admin.utils.MyStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 自定义注解的权限校验的类
 */
@Service(value = "syyo")
public class SyyoPermissionConfig {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SecurityProperties securityProperties;

    public Boolean check(String... permissions) {
        ValueOperations<String, String> redis = redisTemplate.opsForValue();
        boolean b = true;
        String token = request.getHeader(securityProperties.getHeader());
        // 没有传token，或者格式不对，直接返回没有权限
        if (MyStringUtils.isEmpty(token) || token.length() < 7) {
            return false;
        }
        token = token.substring(7);
        String roles = redis.get(token);
        // redis没有存储role，返回没有权限
        if (MyStringUtils.isEmpty(roles)) {
            return false;
        }

        if (!roles.contains("admin")) {
            for (String permission : permissions) {
                b = roles.contains(permission);
            }
        }

//         获取当前用户的所有权限
//        List<String> elPermissions = SecurityUtils.getUserDetails().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
//        boolean b  = true;
//        //判断当前用户是否是admin，admin有所有权限
//        if (!elPermissions.contains("admin")) {
//            //判断当前请求的权限标识是否在当前用户的所有权限中
//            //permissions集合里的值如果在elPermissions集合里只要包含一个，就返回true
//            b = Arrays.stream(permissions).anyMatch(elPermissions::contains);
//        }
        return b;
    }
}
